<?php

namespace App\Http\Controllers\Admin;

use App\Services\LinkService;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller;

class LinkController extends Controller
{

    private $linkService;

    public function __construct(LinkService $linkService)
    {
        $this->linkService = $linkService;
    }

    public function index()
    {
        return view('admin.link.index');
    }

    public function list()
    {
        $data = $this->linkService->getList();
        return success($data);
    }

    public function add(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.link.add');
        }

        $this->validate($request, [
            'link_name'  => 'bail|required|string|max:50',
            'link_url'   => 'bail|required|string|url|max:255',
            'list_order' => 'bail|required|integer',
        ]);

        $data = $request->input();
        $this->linkService->add($data);

        return success();
    }

    public function edit(Request $request)
    {
        if ($request->isMethod('get')) {
            $id = $request->input('id', 0);
            $link = $this->linkService->find($id);
            $data = $link->toArray();
            return view('admin.link.edit', $data);
        }

        $this->validate($request, [
            'id'         => 'bail|required|integer',
            'link_name'  => 'bail|required|string|max:50',
            'link_url'   => 'bail|required|string|url|max:255',
            'list_order' => 'bail|required|integer',
        ]);

        $data = $request->input();
        $this->linkService->edit($data);

        return success();
    }

    public function del(Request $request)
    {
        $id = $request->input('id', 0);
        $this->linkService->del($id);
        return success();
    }

}
